package com.konoha.controller;

import com.konoha.pojo.Result;
import com.konoha.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;


@RestController
public class FileUploadController {

    private final AliOssUtil aliOssUtil;

    @Autowired
    public FileUploadController(AliOssUtil aliOssUtil) {
        this.aliOssUtil = aliOssUtil;
    }


    @PostMapping("/upload")
    public Result<String> upload(@RequestParam("file") MultipartFile file) {
        try {
            // 保证文件名字唯一的，从而防止文件覆盖
            String originalFilename = file.getOriginalFilename();
            String filename = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
            // 调用 AliOssUtil 类的实例方法来上传文件
            String url = aliOssUtil.uploadFile(filename, file.getInputStream());
            System.out.println("row: " + url);
            return Result.success(url);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("File upload failed: " );
        }
    }

}
